package com.youko.backstage.service;

import com.youko.backstage.bean.Merchant;
import com.youko.backstage.mapper.MerchantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MerchantService {
    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private RedisTemplate redisTemplate;


    /**保存商家信息
     *
     * @param merchant
     */
    @CachePut(value = "merchant", key = "#merchant.name")
    public void saveMerchant(Merchant merchant){
        merchantMapper.insertMerchant(merchant);
    }

    /**根据名字查询商家信息
     *
     * @param name
     * @return
     */
    @Cacheable(value = "merchant")
    public Merchant getMerchant(String name){
        return merchantMapper.getMerchantByName(name);
    }

    /**修改密码,待完善springSecurity
     *
     * @param newPassword
     * @return
     */
    public int updatePassword(int id,String newPassword){
//        UserDetails principal = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        String name = principal.getUsername();

        // 通过用户名获取到用户信息（获取密码）
        Merchant merchant = merchantMapper.getMerchantById(id);
        merchantMapper.updatePassword(id, passwordEncoder.encode(newPassword));

        //此处实际应为检测手机短信之类的操作，或者直接在个人中心修改
        return 1;
    }


    /**
     * 添加图片文件服务器端路径
     * @param id
     * @param path
     */
    public void updateMerchantPhotoPath(int id,String path){
        merchantMapper.updateMerchantPhotoPath(id,path);
    }


    /**
     * 修改商家信息（mobile，desc,nickname)
     * @param id
     * @param mobile
     * @param description
     * @param nickname
     * @return
     */
    public int updateInfo(int id,String mobile,String description,String nickname){
        return merchantMapper.updateInfo(id,mobile,description,nickname);
    }


}
